import { Dispatch } from 'redux';
import type { IGlobalState } from './index.d';
import { _getMenus } from '@/api/sys';
import { constantRoutes } from '@/router/router.config';
import useRouters, { useFlattenRoutes } from '@/hooks/useRouters';

export const MUDULE_NAME: string = 'global';

export const types = {
  IS_COLLAPSE: 'IS_COLLAPSE', // 侧边栏展开收起状态
  GLOBAL_SIZE: 'GLOBAL_SIZE', // 全局的组件大小
  GLOBAL_FLATTEN_ROUTERS: 'GLOBAL_FLATTEN_ROUTERS', // 拍平后的router
  GLOBAL_AUTH_ROUTERS: 'GLOBAL_AUTH_ROUTERS', // 全局已授权的router
  GLOBAL_MENU_KEYS: 'GLOBAL_MENU_KEYS', // 菜单key
}

export default (state: IGlobalState = {
  isCollapse: false,
  routers: constantRoutes,
  size: 'middle',
  flattenRouters: useFlattenRoutes(constantRoutes),
  menuKeys: []
}, action: any) => {
  switch (action.type) {
    case types.IS_COLLAPSE:
      return Object.assign({}, state, {
        isCollapse: action.isCollapse
      })
    case types.GLOBAL_AUTH_ROUTERS:
      return Object.assign({}, state, {
        routers: action.routers
      })
    case types.GLOBAL_SIZE:
      return Object.assign({}, state, {
        size: action.size
      })
    case types.GLOBAL_FLATTEN_ROUTERS:
      return Object.assign({}, state, {
        flattenRouters: action.flattenRouters
      })
    case types.GLOBAL_MENU_KEYS:
      return Object.assign({}, state, {
        menuKeys: action.menuKeys
      })
    default: return state;
  }
}

// 改变导航栏状态
export function setCollapse(isCollapse: Boolean) {
  return {
    type: types.IS_COLLAPSE,
    isCollapse
  }
}


// 获取菜单权限
export function setMenus() {
  return async (dispatch: Dispatch): Promise<void> => {
    try {
      const res = await _getMenus();
      const { flattenRouters, routers } = useRouters(res.data);
      // 保存后台取到的key
      dispatch({
        type: types.GLOBAL_MENU_KEYS,
        menuKeys: res.data
      })

      // 设置已授权路由菜单
      dispatch({
        type: types.GLOBAL_AUTH_ROUTERS,
        routers
      });

      // 设计扁平的 路由便于查询使用（未授权）
      dispatch({
        type: types.GLOBAL_FLATTEN_ROUTERS,
        flattenRouters
      });
    } catch (err) {
      console.log(err)
    }
  }
}
